package cn.matezk.lianlian.service.impl;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.hutool.core.util.ObjectUtil;
import cn.matezk.lianlian.dao.*;
import cn.matezk.lianlian.model.Device;
import cn.matezk.lianlian.model.UserDevice;
import cn.matezk.lianlian.service.IMiniAppService;
import com.tencentcloudapi.common.exception.TencentCloudSDKException;
import com.tencentcloudapi.iotexplorer.v20190423.IotexplorerClient;
import com.tencentcloudapi.iotexplorer.v20190423.models.DeviceUser;
import com.tencentcloudapi.iotexplorer.v20190423.models.GetFamilyDeviceUserListRequest;
import com.tencentcloudapi.iotexplorer.v20190423.models.GetFamilyDeviceUserListResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class MiniAppService implements IMiniAppService {
    @Autowired
    private UserDao userDao;
    @Autowired
    private DeviceDao deviceDao;
    @Autowired
    private UserDeviceDao userDeviceDao;
    @Autowired
    private FamilyMemberDao familyMemberDao;
    @Autowired
    private NotifyTemplateDao notifyTemplateDao;
    @Autowired
    private WxMaService wxMaService;
    @Autowired
    private IotexplorerClient tencentClient;

    public String aliasName(String productId, String deviceName) {
        String deviceId = productId.concat("/").concat(deviceName);
        Device device = deviceDao.selectByPrimaryKey(deviceId);
        return ObjectUtil.isNotNull(device) ? device.getAliasName() : null;
    }

    @Override
    public void updateDevice(Device device) {
        deviceDao.updateByPrimaryKeySelective(device);
    }

    @Override
    public void bindDevice(UserDevice userDevice) {
        UserDevice ud = userDeviceDao.match(userDevice.getUserId(), userDevice.getDeviceId());
        if (ObjectUtil.isNotNull(ud)) return;
        userDeviceDao.bind(userDevice);
    }

    @Override
    public void unbindDevice(UserDevice userDevice) {
        userDeviceDao.unbind(userDevice.getUserId(), userDevice.getDeviceId());
    }

    @Override
    public void joinFamily(String familyId, String userId) {
        familyMemberDao.bind(familyId, userId);
    }

    @Override
    public void removeFamily(String familyId, String userId) {
        familyMemberDao.unbind(familyId, userId);
    }

    @Override
    public void transferFamily(String familyId, String fromUserId, String toUserId) {
        userDeviceDao.changeFamilyDeviceOwner(familyId, fromUserId, toUserId);
    }

    @Override
    public DeviceUser[] deviceUser(String productId, String deviceName) throws TencentCloudSDKException {
        GetFamilyDeviceUserListRequest request = new GetFamilyDeviceUserListRequest();
        request.setProductId(productId);
        request.setDeviceName(deviceName);
        GetFamilyDeviceUserListResponse response = tencentClient.GetFamilyDeviceUserList(request);
        return response.getUserList();
    }
}
